package com.example.myapplicationktkt2.ui

import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.myapplicationktkt2.R
import com.example.myapplicationktkt2.log.Logger
import java.io.File
import java.io.FileInputStream
import java.util.Scanner

class LogViewerActivity : AppCompatActivity() {
    private lateinit var logTextView: TextView
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_log_viewer)
        val root = findViewById<View>(android.R.id.content)
        ViewCompat.setOnApplyWindowInsetsListener(root) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        
        logTextView = findViewById(R.id.logTextView)
        
        val btnRefresh = findViewById<Button>(R.id.btnRefresh)
        val btnClear = findViewById<Button>(R.id.btnClear)
        
        btnRefresh.setOnClickListener {
            loadLogs()
        }
        
        btnClear.setOnClickListener {
            clearLogs()
        }
        
        loadLogs()
    }
    
    private fun loadLogs() {
        try {
            val logFile = File(getExternalFilesDir(null), "app_log.txt")
            if (logFile.exists()) {
                val scanner = Scanner(FileInputStream(logFile))
                val logContent = StringBuilder()
                while (scanner.hasNextLine()) {
                    logContent.append(scanner.nextLine()).append("\n")
                }
                scanner.close()
                logTextView.text = logContent.toString()
            } else {
                logTextView.text = "暂无日志"
            }
        } catch (e: Exception) {
            logTextView.text = "读取日志失败: ${e.message}"
        }
    }
    
    private fun clearLogs() {
        try {
            val logFile = File(getExternalFilesDir(null), "app_log.txt")
            if (logFile.exists()) {
                logFile.delete()
                logTextView.text = "日志已清空"
                Logger.i("LogViewerActivity", "日志已清空")
            }
        } catch (e: Exception) {
            logTextView.text = "清空日志失败: ${e.message}"
        }
    }
}